<?php

namespace app\common\model;

use think\Model;
use Carbon\Carbon;
use app\common\traits\model\TraitModel;

class Holidays extends Model
{
	use TraitModel;

	protected $resultSetType = '';

    public static function tableLog($a, $u)
    {
    	//\think\Db::table('logs')->insert(['user_id' => 1, 'type' => $a, 'remark' => json_encode($u)]);
    }
	public function updateInfo($info_array = [], $where = [])
	{
		return self::update($info_array, $where, true);
	}
	public function initHolidays($y = 1)
	{
		$diffday = Carbon::now()->addYear($y)->diffInDays(Carbon::now());

		if ($datetimes = $this->order('datetimes', 'desc')->value('datetimes')) {
			$diffday = Carbon::now()->addYear($y)->diffInDays(Carbon::createFromFormat('Y-n-j', $datetimes));
		}
		if ($diffday > 1) {
			$this->startTrans();
			try {
				for ($i=0; $i < $diffday; $i++) { 
					$datetimes = Carbon::now()->addDay($i);
					$is_holiday = 0;
					if ($datetimes->isWeekend()) {
						$is_holiday = 1;
					}
					$this->create(['year' => $datetimes->year, 'month' => $datetimes->month, 'day'=> $datetimes->day, 'is_holiday' => $is_holiday, 'datetimes' => $datetimes->toDateString()]);
				}
				$this->commit();

			} catch (\Exception $e) {
				$this->rollback();
				return false;
			}
		}
		return true;
	}
	/**
	 * [holiday description]
	 * @param  [type] $year  [description]
	 * @param  [type] $month [description]
	 * @param  [type] $days  [description]
	 * @return [type]        [description]
	 */
	public function holiday($year, $month = null, $days = null)
	{
		$this->field('datetimes, is_holiday');
		if (empty($month)) {
			$date = $year;
			if (is_string($date)) {
				if (strpos($date, ',')) {
					$date = explode(',', $date);
					$this->where(['datetimes' => ['in', $date]]);
				}else{
					return $this->where(['datetimes' => $date])->find();
				}
				
			}else{
				$this->where(['datetimes' => ['in', $date]]);
			}
		}else{
			if (empty($days)) {
				$this->where(['year' => $year, 'month' => $month]);
			}else {
				if (is_string($days) || is_int($days)) {
					if (strpos($days, ',')) {
						$days = explode(',', $days);
						$this->where(['year' => $year, 'month' => $month, 'day' => ['in', $date]]);
					}else{
						return $this->where(['year' => $year, 'month' => $month, 'day' => $days])->find();
					}
				}else{
					$this->where(['year' => $year, 'month' => $month, 'day' => ['in', $days]]);
				}
			}
		}
		if ($res = $this->select()) {
			return $res;
		}
		return ;
		
	}
}

